package cn.tedu.icop.order.xxljob;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.client.ExecutorBizClient;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.biz.model.TriggerParam;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.glue.GlueTypeEnum;
import org.junit.jupiter.api.Assertions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class XxlJobService {

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    @Value("${xxl.job.login.username}")
    private String username;

    @Value("${xxl.job.login.password}")
    private String password;

    private final RestTemplate restTemplate;

    public XxlJobService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    private String cookie;
    @PostConstruct
    public void init(){
        System.out.println("adminAddresses="+adminAddresses);
        cookie=login();
    }

    public String login(){
        // 登录获取 token
        String loginUrl = adminAddresses + "/login";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userName", username);
        map.add("password", password);
        System.out.println("map="+map);

        HttpEntity<MultiValueMap<String, String>> entity =
                new HttpEntity<>(map, headers);
        ResponseEntity<String> response =
                restTemplate.postForEntity(loginUrl, entity, String.class);
        System.out.println("response="+response);
        // 检查登录响应
        if (response.getStatusCode().is2xxSuccessful()) {
            System.out.println("Login successful");
        } else {
            System.out.println("Login failed with status code: " + response.getStatusCode());
            System.out.println("Response body: " + response.getBody());
            return null;
        }
        // 获取 Cookie
        List<String> cookies = response.getHeaders().get(HttpHeaders.SET_COOKIE);
        if (cookies == null || cookies.isEmpty()) {
            System.out.println("No cookies received from login response");
            return null;
        }
        String cookie = String.join("; ", cookies);
        System.out.println("Received cookies: " + cookie);
        return cookie;
    }
    public String addJob( MultiValueMap<String, String> map) {
        // 触发任务
        String triggerUrl = adminAddresses + "/jobinfo/add";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set(HttpHeaders.COOKIE, cookie);
        headers.set("Authorization", "Bearer " + accessToken);
        HttpEntity<MultiValueMap<String, String>>  entity =
                new HttpEntity<>(map, headers);
        ResponseEntity<String> response =
                restTemplate.postForEntity(triggerUrl, entity, String.class);
        System.out.println("80.response="+ response);
        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            System.out.println("Job triggered successfully: " + response.getBody());
        } else {
            System.out.println("Failed to trigger job: " + response.getBody() + " with status code: " + response.getStatusCode());
            System.out.println("Response body: " + response.getBody());
        }
        JSONObject jsonObject = JSON.parseObject(response.getBody());
        String jobId = (String)jsonObject.get("content");
        return jobId;
    }
    public void triggerJob(Integer jobId) {
        // 触发任务
        String triggerUrl = adminAddresses + "/jobinfo/start";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set(HttpHeaders.COOKIE, cookie);
        headers.set("Authorization", "Bearer " + accessToken);

        LinkedMultiValueMap map = new LinkedMultiValueMap<>();
        map.add("id", String.valueOf(jobId));

        HttpEntity<MultiValueMap<String, String>>  entity =
                new HttpEntity<>(map, headers);
        ResponseEntity<String> response =
                restTemplate.postForEntity(triggerUrl, entity, String.class);
        System.out.println("80.response="+ response);
        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            System.out.println("Job triggered successfully: " + jobId);
        } else {
            System.out.println("Failed to trigger job: " + jobId + " with status code: " + response.getStatusCode());
            System.out.println("Response body: " + response.getBody());
        }
    }
    public void run(Integer jobId,String orderNo){
        String addressUrl = "http://127.0.0.1:9999/";
        String accessToken = "default_token";
        //官方文档-触发型
        ExecutorBiz executorBiz = new ExecutorBizClient(addressUrl, accessToken);
        // trigger data
        final TriggerParam triggerParam = new TriggerParam();
        triggerParam.setJobId(jobId);
        triggerParam.setExecutorHandler("doCheckTimeoutOrder");
        triggerParam.setExecutorParams(orderNo);//null
        triggerParam.setExecutorBlockStrategy(ExecutorBlockStrategyEnum.COVER_EARLY.name());
        triggerParam.setGlueType(GlueTypeEnum.BEAN.name());//BEAN
        triggerParam.setGlueSource(null);
        triggerParam.setGlueUpdatetime(System.currentTimeMillis());
        triggerParam.setLogId(1);
        triggerParam.setLogDateTime(System.currentTimeMillis());
        // Act (触发任务)
        final ReturnT<String> retval = executorBiz.run(triggerParam);
        System.out.println("retval="+retval);
        // Assert result
        Assertions.assertNotNull(retval);
    }
    public static String generateCronExpressionFor2MinutesLater() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime later = now.plusMinutes(1);//在当前时间的基础上加1分钟

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ss mm HH dd MM ? yyyy");//cron
        return later.format(formatter);
    }
}